<?php

class Default_Model_MediaIndex
{
    var $Groups;

    function __construct ($silent=NULL) {
        if (!$silent) $this->LoadGroups();
    }

    function LoadGroups ($detail=NULL) 
    { 
        $det = "SELECT COUNT(articleid) as filmcount,
                groupname, articleid, subject FROM MediaIndex 
                GROUP BY groupname
                ORDER BY groupname";
        $sql = "SELECT DISTINCT groupname FROM MediaIndex ORDER BY groupname";        
        $db  = new Usenet_Connector;
        $ret = $db->Execute ($detail ? $det : $sql);
        $db->Close();

        $this->Groups = array();
        while($row = mysql_fetch_assoc($ret)) {
            $this->Groups[] = $detail ? $row : $row['groupname'];
        } 
    } 

    public function GetFiles($groupname, $detail=NULL)
    { 
        $xml  = NULL;
        $path = NULL;
        $sql  = "SELECT * FROM MediaIndex WHERE groupname = '{$groupname}' ORDER BY subject";
        $db   = new Usenet_Connector;
        $ret  = $db->Execute ($sql);

        $db->Close(); 
        $this->Files = array(); 

        while($row = mysql_fetch_assoc($ret)) { 
            if ($detail) {
                $row['name'] = '(Unknown sender)';
                if ($row['filename']!=$path) {
                    $path = $row['filename'];
                    $xml  = simplexml_load_file($path); 
                }  
                $key = $row['articleid'];
                $ref = $xml->xpath ("//items/article[contains(id, '{$key}')]/../..");
                foreach ($ref as $e) $row['name'] = (string) $e->name;
            }
            $this->Files[] = $row;
        }  
    } 

    public function GetArticle($groupname, $id)
    {  
        $sql = "SELECT * FROM MediaIndex WHERE groupname = '{$groupname}' AND articleid = '{$id}'"; 
        $db  = new Usenet_Connector;
        $ret = $db->Execute ($sql);
 
        if($row = mysql_fetch_assoc($ret)) {
            $this->Article = $row;
        }  
        $db->Close(); 

        $this->GetFiles ($groupname);
    }

}

